<?php
define('ISOVER', false);
define('AWARD0', 3);
define('AWARD1', 5);
define('AWARD2', 60);
define('AWARD3', 60);
define('AWARD4', 872);
define('SALT', '2020yzwcv2'); //签名加点盐
define('COOKIEPRE', 'yzwcv2_');
define('COOKIETTL', 31536000); //一年

header('content-type:text/html;charset=utf-8');
date_default_timezone_set('Asia/Shanghai');

require_once './inc/forbid.inc.php';

function getToken($id, $award, $name)
{
    return substr(md5($id . $award . $name . SALT), 0, 6);
}

function getAward()
{
    $a = AWARD4; //优秀奖：[1, a]
    $b = $a + AWARD3; //三等奖：[a+1, b];
    $c = $b + AWARD2; //二等奖：[b+1, c];
    $d = $c + AWARD1; //一等奖: [c+1, d];
    $e = $d + AWARD0; //特等奖: [d+1, e];
    $n = rand(1, $e);
    if ($n <= $a)
        return 4;
    if ($n <= $b)
        return 3;
    if ($n <= $c)
        return 2;
    if ($n <= $d)
        return 1;
    return 0;
}

function reply($id, $award, $name, $token)
{
    $reply['status'] = 'success';
    $reply['id'] = $id;
    $reply['award'] = $award;
    $reply['name'] = $name;
    $reply['token'] = $token;
    echo json_encode($reply);
}

function writeLog($id, $award, $name, $token)
{
    $line = date('m/d H:i:s', time()) . ' ' . $id . ' ' . $award . ' ' . $name . ' ' . $token . ' ' . $_SERVER["REMOTE_ADDR"] . "\r\n";
    file_put_contents('logs.php', $line, FILE_APPEND);
}


if (!empty($_POST['name'])) {
    if (ISOVER) {
        echo '{"status":"over"}';
        exit();
    }
    if (!empty($_COOKIE[COOKIEPRE . 'token'])) {
        echo '{"status":"already"}';
        exit();
    }
    $fbd = new Forbid();
    if ($fbd->isForbid()) {
        if ($fbd->is_always_forbid == true)
            echo '{"status":"always_forbid"}';
        else
            echo '{"status":"forbid"}';
        exit();
    }

    $id = 1;
    if (!is_file('logs.php'))
        file_put_contents('logs.php', '<?php exit(); ?>' . "\r\n");
    else
        $id = count(file('./logs.php'));
    $award = getAward();
    if ($id > 1000) //超过1000人，之后全部都是优秀奖
        $award = 4;
    $name = $_POST['name'];
    $token = getToken($id, $award, $name);
    setcookie(COOKIEPRE . 'id', $id, time() + COOKIETTL);
    setcookie(COOKIEPRE . 'award', $award, time() + COOKIETTL);
    setcookie(COOKIEPRE . 'name', $name, time() + COOKIETTL);
    setcookie(COOKIEPRE . 'token', $token, time() + COOKIETTL);
    writeLog($id, $award, $name, $token);
    reply($id, $award, $name, $token);
    exit();
}